package cn.com.backstage.controller;

import java.io.File;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.com.api.entity.ApiGoods;
import cn.com.api.entity.ApiGoodsTopicLink;
import cn.com.api.entity.ApiGoods_p;
import cn.com.api.entity.ApiShop;
import cn.com.api.entity.ApiSpeicalChang;
import cn.com.api.entity.ApiT_brand;
import cn.com.api.entity.ApiT_city;
import cn.com.api.entity.ApiT_goods_tags;
import cn.com.api.entity.ApiT_goods_tags_link;
import cn.com.api.entity.ApiT_goods_topic;
import cn.com.api.entity.ApiT_member_entrepreneur;
import cn.com.api.entity.ApiT_products;
import cn.com.api.entity.ApiType;
import cn.com.api.service.ApiErpService;
import cn.com.api.service.ApiGoodsService;
import cn.com.api.service.ApiShopsService;
import cn.com.api.service.ApiT_brandService;
import cn.com.api.service.ApiT_cityService;
import cn.com.api.service.ApiT_goods_tagsService;
import cn.com.api.service.ApiT_goods_tags_linkService;
import cn.com.api.service.ApiT_goods_topicService;
import cn.com.api.service.ApiT_goods_topic_linkService;
import cn.com.api.service.ApiT_member_entrepreneurService;
import cn.com.api.service.ApiT_productsService;
import cn.com.api.service.ApiTypeService;
import cn.com.api.service.StartOnLoadService;
import cn.com.uthink.util.DateTimeUtil;
import cn.com.util.*;
import net.sf.json.JSONObject;

@Controller
@RequestMapping(Utils.SYS_BACKSTAGE)
public class GoodsController {

	private static Logger logger = Logger.getLogger(GoodsController.class);

	@Autowired
	private ApiGoodsService goodService;
	@Autowired
	private ApiTypeService apiTypeService;
	@Autowired
	private ApiT_productsService apiT_productsService;
	@Autowired
	private ApiShopsService apiShopsService;
	@Autowired
	private StartOnLoadService startOnLoadService;
	@Autowired
	private ApiErpService apiErpService;
	@Autowired
	private ApiT_cityService apiT_cityService;
	@Autowired
	private ApiT_brandService apiT_brandService;
	@Autowired
	private ApiT_goods_tagsService apiT_goods_tagsService;
	@Autowired
	private ApiT_goods_tags_linkService apiT_goods_tags_linkService;
	@Autowired
	private ApiT_goods_topicService apiT_goods_topicService;
	@Autowired
	private ApiT_goods_topic_linkService apiT_goods_topic_linkService;
	@Autowired
	private ApiT_member_entrepreneurService apiT_member_entrepreneurService;

	/**
	 * 自营店商品list
	 * 
	 * @return
	 */
	@RequestMapping(value = "goods-list")
	public ModelAndView goods_list(HttpServletRequest request, HttpServletResponse response, PageInfo pageInfo)
			throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/goods_list.jsp");
		// c_mtype : 0用户 1 绑定商户 2 vip 9被屏蔽 3 配送员

		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("isZiYing", true);
		conditions.put("cEnable", true);

		List<ApiGoods> goods_list = goodService.searchGoods(conditions, pageInfo);
		mv.addObject("goods_list", goods_list);

		//
		List<ApiShop> shops = apiShopsService.searchShops(conditions);
		mv.addObject("shops", shops);

		List<ApiT_city> citys = startOnLoadService.citys();
		mv.addObject("citys", citys);

		List<ApiType> types = new ArrayList<ApiType>();
		List<ApiType> types1 = null;
		types1 = apiTypeService.getBigTypesZiYing();

		// 包含根级分类
		types.addAll(types1);
		List<ApiType> types2 = apiTypeService.getSecondTyes(true);
		types.addAll(types2);
		List<ApiType> types3 = apiTypeService.getThirdTypes(true);
		types.addAll(types3);

		mv.addObject("types1", types1);
		mv.addObject("types2", types2);
		mv.addObject("types3", types3);
		mv.addObject("types", types);
		mv.addObject("isZiYing", true);

		return mv;
	}

	/**
	 * 自营店商品list
	 * 
	 * @return
	 */
	@RequestMapping(value = "sear-goods-list")
	public ModelAndView sear_goods_list(HttpServletRequest request, HttpServletResponse response, PageInfo pageInfo)
			throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/select_goods.jsp");
		// c_mtype : 0用户 1 绑定商户 2 vip 9被屏蔽 3 配送员

		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("isZiYing", true);
		conditions.put("cEnable", true);

		List<ApiGoods> goods_list = goodService.searchGoods(conditions, pageInfo);
		mv.addObject("goods_list", goods_list);

		//
		List<ApiShop> shops = apiShopsService.searchShops(conditions);
		mv.addObject("shops", shops);

		List<ApiT_city> citys = startOnLoadService.citys();
		mv.addObject("citys", citys);

		List<ApiType> types = new ArrayList<ApiType>();
		List<ApiType> types1 = null;
		types1 = apiTypeService.getBigTypesZiYing();

		// 包含根级分类
		types.addAll(types1);
		List<ApiType> types2 = apiTypeService.getSecondTypes();
		types.addAll(types2);
		List<ApiType> types3 = apiTypeService.getThirdTypes();
		types.addAll(types3);

		mv.addObject("types1", types1);
		mv.addObject("types2", types2);
		mv.addObject("types3", types3);
		mv.addObject("types", types);
		mv.addObject("isZiYing", true);

		return mv;
	}

	/**
	 * 自营店查询商品
	 * 
	 * @return
	 */
	@RequestMapping(value = "goods-search")
	public ModelAndView goods_search(ApiGoods searhGoods, HttpServletRequest request, HttpServletResponse response,
			Boolean isZiYing, PageInfo pageInfo) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/goods_list.jsp");
		// c_mtype : 0用户 1 绑定商户 2 vip 9被屏蔽 3 配送员

		Map<String, Object> conditions = new HashMap<String, Object>();
		String name = request.getParameter("name");
		String type = request.getParameter("type");
		String type1 = request.getParameter("type1");
		String type2 = request.getParameter("type2");
		String type3 = request.getParameter("type3");
		String shopId = request.getParameter("shopId");
		String is_deleted = request.getParameter("is_deleted");
		String status = request.getParameter("status");
		conditions.put("name", name != null ? name.trim() : name);
		conditions.put("type", type != null ? type.trim() : type);
		conditions.put("type1", type1 != null ? type1.trim() : type1);
		conditions.put("type2", type2 != null ? type2.trim() : type2);
		conditions.put("type3", type3 != null ? type3.trim() : type3);
		conditions.put("is_deleted", is_deleted);
		conditions.put("status", status);
		conditions.put("shopId", shopId);
		conditions.put("isZiYing", true);
		conditions.put("cEnable", true);

		List<Integer> endTypes = new ArrayList<Integer>();
		Integer parentTypeId = Integer.parseInt(type);

		if (parentTypeId != -1) {
			endTypes.add(parentTypeId);
		}

		// 二级
		List<Integer> seconedTypes = apiTypeService.getZiYingSubTypes(parentTypeId);
		// 三级
		for (Integer parentId : seconedTypes) {
			List<Integer> subs = apiTypeService.getZiYingSubTypes(parentId);
			endTypes.addAll(subs);
		}
		endTypes.addAll(seconedTypes);

		conditions.put("types", endTypes);

		mv.addObject("conditions", conditions);
		mv.addObject("isZiYing", isZiYing);
		List<ApiGoods> goods_list = goodService.searchGoods(conditions, pageInfo);
		mv.addObject("goods_list", goods_list);

		//
		List<ApiShop> shops = apiShopsService.searchShops(conditions);
		mv.addObject("shops", shops);

		List<ApiT_city> citys = startOnLoadService.citys();
		mv.addObject("citys", citys);

		List<ApiType> types = new ArrayList<ApiType>();
		List<ApiType> types1 = apiTypeService.getBigTypesZiYing();
		// 包含根级分类
		types.addAll(types1);
		List<ApiType> types2 = apiTypeService.getSecondTyes(true);
		types.addAll(types2);
		List<ApiType> types3 = apiTypeService.getThirdTypes(true);
		types.addAll(types3);

		ApiType goodsType = apiTypeService.findTypeById(Integer.valueOf(type));

		mv.addObject("types1", types1);
		mv.addObject("types2", types2);
		mv.addObject("types3", types3);
		mv.addObject("types", types);
		mv.addObject("pageInfo", pageInfo);

		return mv;
	}

	/**
	 * 非自营店查询商品
	 * 
	 * @return
	 */
	@RequestMapping(value = "goods-search2")
	public ModelAndView goods_search2(ApiGoods searhGoods, HttpServletRequest request, HttpServletResponse response,
			PageInfo pageInfo) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/goods_list2.jsp");
		// c_mtype : 0用户 1 绑定商户 2 vip 9被屏蔽 3 配送员

		Map<String, Object> conditions = new HashMap<String, Object>();
		String name = request.getParameter("name");
		String type = request.getParameter("type");
		String type1 = request.getParameter("type1");
		String type2 = request.getParameter("type2");
		String type3 = request.getParameter("type3");
		String shopId = request.getParameter("shopId");
		String shopName = request.getParameter("shopName");
		String is_deleted = request.getParameter("is_deleted");
		String status = request.getParameter("status");
		conditions.put("name", name);
		conditions.put("type", type);
		conditions.put("type1", type1);
		conditions.put("type2", type2);
		conditions.put("type3", type3);
		conditions.put("is_deleted", is_deleted);
		conditions.put("status", status);
		conditions.put("shopId", shopId);
		conditions.put("shopName", shopName);
		conditions.put("isZiYing", false);
		conditions.put("cEnable", true);

		List<Integer> endTypes = new ArrayList<Integer>();
		Integer parentTypeId = Integer.parseInt(type);
		if (parentTypeId != -1) {
			endTypes.add(parentTypeId);
		}
		// 二级
		List<Integer> seconedTypes = apiTypeService.getNoZiYingSubTypes(parentTypeId);
		// 三级
		for (Integer parentId : seconedTypes) {
			List<Integer> subs = apiTypeService.getNoZiYingSubTypes(parentId);
			endTypes.addAll(subs);
		}
		endTypes.addAll(seconedTypes);

		conditions.put("types", endTypes);

		mv.addObject("conditions", conditions);
		mv.addObject("isZiYing", false);
		List<ApiGoods> goods_list = goodService.searchGoods(conditions, pageInfo);
		mv.addObject("goods_list", goods_list);

		List<ApiShop> shops = apiShopsService.searchShops(conditions);
		mv.addObject("shops", shops);

		List<ApiT_city> citys = startOnLoadService.citys();
		mv.addObject("citys", citys);

		List<ApiType> types = new ArrayList<ApiType>();
		List<ApiType> types1 = apiTypeService.getBigTypes();

		// 包含根级分类
		types.addAll(types1);
		List<ApiType> types2 = apiTypeService.getSecondTyes(false);
		types.addAll(types2);
		List<ApiType> types3 = apiTypeService.getThirdTypes(false);
		types.addAll(types3);

		mv.addObject("types1", types1);
		mv.addObject("types2", types2);
		mv.addObject("types3", types3);
		mv.addObject("types", types);

		ApiType goodsType = apiTypeService.findTypeById(Integer.valueOf(type));
		mv.addObject("pageInfo", pageInfo);

		return mv;
	}

	/**
	 * 非自营店查询商品
	 * 
	 * @return
	 */
	@RequestMapping(value = "sear-act-goods")
	public ModelAndView sear_act_goods(PageInfo pageInfo, ApiGoods searhGoods, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/select_goods.jsp");
		String name = request.getParameter("name");
		String cityid = request.getParameter("cityid");
		String isone = request.getParameter("isone");
		String act_type_id = request.getParameter("act_type_id");
		String city_id = request.getParameter("city_id");
		// c_mtype : 0用户 1 绑定商户 2 vip 9被屏蔽 3 配送员

		if (isone == null) {
			List<Map<String, Object>> goods_list = null;
			Map<String, Object> conditions = new HashMap<String, Object>();
			conditions.put("name", name);
			conditions.put("cityid", cityid);
			String str = startOnLoadService.dictionaryMap().get("ACT_XINREN");
			if (act_type_id != null && act_type_id != "" && str.equals(act_type_id)) {
				conditions.put("type", act_type_id);
				goods_list = goodService.searActGoodsByTypeListPage(conditions, pageInfo);
			} else {
				conditions.put("type", str); /* mapper条件为不等于 当前type */
				goods_list = goodService.searActGoodsListPage(conditions, pageInfo);
			}
			mv.addObject("conditions", conditions);
			mv.addObject("goods_list", goods_list);
		}
		if (act_type_id != null) {
			mv.addObject("act_type_id", act_type_id);
		}
		mv.addObject("pageInfo", pageInfo);

		return mv;
	}

	/**
	 * 查询商品
	 * 
	 * @return
	 */
	@RequestMapping(value = "sear-act-goods-type")
	public ModelAndView sear_act_goods_type(PageInfo pageInfo, ApiGoods searhGoods, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/findGoodsActType.jsp");
		String name = request.getParameter("name");
		String cityid = request.getParameter("cityid");
		String isone = request.getParameter("isone");
		String typeid = request.getParameter("typeid");
		if (isone == null) {
			List<Map<String, Object>> goods_list = new ArrayList<Map<String, Object>>();
			goods_list = goodService.searGoodsActTypeListPage(typeid, cityid, name, pageInfo);
			mv.addObject("goods_list", goods_list);
			mv.addObject("typeid", typeid);
			mv.addObject("cityid", cityid);
			mv.addObject("name", name);
			mv.addObject("pageInfo", pageInfo);
		}

		return mv;
	}

	@RequestMapping(value = "get-allCities")
	public @ResponseBody List<ApiT_city> getAllCities() {

		List<ApiT_city> cities = startOnLoadService.citys();
		return cities;
	}

	/**
	 * 活动商品（一元购）进入新增页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "goods-activ-add-pre")
	public ModelAndView goods_activ_add_pre(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/goods_activ_add.jsp");
		//
		List<ApiT_city> citys = startOnLoadService.citys();
		mv.addObject("citys", citys);

		List<ApiType> promotion_types = startOnLoadService.promotion_types();
		mv.addObject("promotion_types", promotion_types);

		mv.addObject("isZiYing", true);

		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("isZiYing", true);
		conditions.put("cEnable", true);

		// 请求编辑某个goods
		if (request.getParameter("id") != null) {
			String id = request.getParameter("id");
			ApiGoods goods = goodService.findT_goodsById(Long.valueOf(id));
			mv.addObject("goods", goods);
			mv.addObject("isEdit", 1);// 用于在页面上判断是不是编辑某个商品
			ApiType goodsType = apiTypeService.findTypeById(goods.getType());
			mv.addObject("goodsType", goodsType);

			// 这个商品所在城市的其它商店
			conditions.put("cityId", goods.getCity_id());
			List<ApiShop> shops = apiShopsService.searchShops(conditions);
			mv.addObject("shops", shops);

			initializeTypes(mv, goodsType);
			// products
			String products_list = "";
			List<ApiT_products> products = apiT_productsService.getUndeletedProductsByGoodsId(Long.valueOf(id));

			mv.addObject("products_list", products_list);
			mv.addObject("products", products);
			if (products.size() <= 0)
				mv.addObject("no_product", 1);
			else
				mv.addObject("no_product", 0);
			// goods' pics
			String image_list = "";
			List<ApiGoods_p> allGoodsImages = goodService.findAllGoodsPByGoodsId(Long.valueOf(id));
			List<ApiGoods_p> images = new ArrayList<ApiGoods_p>();
			List<ApiGoods_p> detailPics = new ArrayList<ApiGoods_p>();
			for (ApiGoods_p image : allGoodsImages) {
				if (image.getType() == 0) {// 商品的多图
					image_list += image.getPath() + ", ";
					images.add(image);
				} else if (image.getType() == 1) {// 商品详情图片
					detailPics.add(image);
				}
			}
			mv.addObject("images", images);
			mv.addObject("detailPics", detailPics);
			mv.addObject("image_list", image_list);
			mv.addObject("productSize", products.size());
		} else {// 新增商品
			List<ApiType> types1 = apiTypeService.getBigTypesZiYing();
			mv.addObject("types1", types1);
			mv.addObject("productSize", 1);// 用于在页面是标识规格 （规格1）
		}
		//
		return mv;
	}

	/**
	 * 活动商品（一元购）list
	 * 
	 * @return
	 */
	@RequestMapping(value = "goods-activ-list")
	public ModelAndView goods_activ_list(HttpServletRequest request, HttpServletResponse response, PageInfo pageInfo)
			throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/goods_activ_list.jsp");
		// c_mtype : 0用户 1 绑定商户 2 vip 9被屏蔽 3 配送员

		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("isZiYing", true);
		conditions.put("cEnable", true);
		// 一元购分类
		String code = startOnLoadService.dictionaryMap().get("ACT_XINREN");

		List<Integer> types = new ArrayList<Integer>();
		ApiType _type = apiTypeService.findTypeById(Integer.valueOf(code));
		types.add(_type.getcCode());
		conditions.put("types", types);

		List<ApiGoods> goods_list = goodService.searchGoods(conditions, pageInfo);
		mv.addObject("goods_list", goods_list);

		//
		List<ApiShop> shops = apiShopsService.searchShops(conditions);
		mv.addObject("shops", shops);

		List<ApiT_city> citys = startOnLoadService.citys();
		mv.addObject("citys", citys);

		mv.addObject("isZiYing", true);

		return mv;
	}

	/**
	 * 保存一元购商品
	 * 
	 * @param request
	 * @param response
	 * @param detailPic
	 *            商品详情图片
	 * @param deletePic
	 *            要删除的详情图片
	 * @throws Exception
	 */
	@Transactional
	@RequestMapping(value = "goods-activ-add")
	public void goods_activ_add(HttpServletRequest request, HttpServletResponse response, String[] detailPic,
			String[] deletePic) throws Exception {
		String name = request.getParameter("name");
		String city_id = request.getParameter("city_id");
		String shop_id = request.getParameter("shop_id");
		if (shop_id == null) {
			ApiShop shop = apiShopsService.searchShopsZiYingByCityId(city_id);
			shop_id = shop.getcId().toString();
		}
		String mini_buy = request.getParameter("mini_buy");
		String image = request.getParameter("image");
		// 一元购
		String type = startOnLoadService.dictionaryMap().get("ACT_XINREN");
		String sort = request.getParameter("sort");
		String producing_area = request.getParameter("producing_area");
		String count = request.getParameter("count");
		String description = request.getParameter("description");
		String is_deleted = request.getParameter("is_deleted");
		if (is_deleted == null)
			is_deleted = "0";
		//
		String products_list = request.getParameter("products_list");
		String image_list = request.getParameter("image_list");
		String image_list_del = request.getParameter("image_list_del");
		String status = request.getParameter("status");
		String property = request.getParameter("property");

		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		// add
		if (id == null || (id.trim()).equals("")) {
			ApiGoods t_good = new ApiGoods();

			t_good.setName(name);
			t_good.setCity_id(Integer.valueOf(city_id));
			t_good.setShop_id(Integer.valueOf(shop_id));
			t_good.setMini_buy(Integer.valueOf(mini_buy));
			t_good.setCount(Integer.valueOf(count));
			t_good.setSort(Integer.valueOf(sort));
			t_good.setProducing_area(producing_area);
			t_good.setType(Integer.valueOf(type));
			t_good.setDescription(description);
			t_good.setImage(image);
			t_good.setStatus(status);
			t_good.setProperty(property);
			Date creteTime = new Date();
			// t_good.setCreate_time(creteTime);
			// t_good.setUpdate_time(creteTime);
			Integer ret_i = goodService.insertT_goodsAll(t_good, products_list, image_list, detailPic, null);
			//
			if (ret_i > 0) {
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "添加成功！");
			}
		}
		// edit
		else {
			ApiGoods t_good = goodService.findT_goodsById(Long.valueOf(id));

			t_good.setName(name);
			t_good.setCity_id(Integer.valueOf(city_id));
			t_good.setShop_id(Integer.valueOf(shop_id));
			t_good.setMini_buy(Integer.valueOf(mini_buy));
			t_good.setCount(Integer.valueOf(count));
			t_good.setSort(Integer.valueOf(sort));
			t_good.setProducing_area(producing_area);
			t_good.setType(Integer.valueOf(type));
			t_good.setIs_deleted(Integer.valueOf(is_deleted));
			t_good.setDescription(description);
			t_good.setImage(image);
			t_good.setStatus(status);
			t_good.setProperty(property);
			Date updateTime = new Date();
			// t_good.setUpdate_time(updateTime);
			if (image_list_del == null)
				image_list_del = ",";
			int ret_i = goodService.updateT_goodsAll(t_good, products_list, image_list, image_list_del, deletePic,
					detailPic);
			//
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "编辑成功！");
		}
		//
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 自营进入新增页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "goods-add-pre")
	public ModelAndView goods_add_pre(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/goods_add.jsp");
		//
		List<ApiT_city> citys = startOnLoadService.citys();
		mv.addObject("citys", citys);

		List<ApiType> promotion_types = startOnLoadService.promotion_types();
		mv.addObject("promotion_types", promotion_types);

		mv.addObject("isZiYing", true);

		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("isZiYing", true);
		conditions.put("cEnable", true);

		HashMap map = new HashMap();
		map.put("disabled", 1);// 可用的品牌
		// 加载品牌列表
		List<ApiT_brand> brandList = apiT_brandService.findT_brandsByMap(map);
		mv.addObject("brandList", brandList);
		// 获取商品标签列表
		List<ApiT_goods_tags> taglist = new ArrayList<ApiT_goods_tags>();

		// 请求编辑某个goods
		if (request.getParameter("id") != null) {
			String id = request.getParameter("id");
			taglist = apiT_goods_tagsService.findGoodsTagss(Long.valueOf(id));

			ApiGoods goods = goodService.findT_goodsById(Long.valueOf(id));
			if (goods != null) {
				// 根据商品编码同步
				/*
				 * List<Map<String, Object>> cur_t_products =
				 * apiT_productsService.findProductsByGoodsId(Long.valueOf(id));
				 * for (Map<String, Object> product : cur_t_products) { Object
				 * _str_erp_product_id = product.get("product_id"); JSONObject
				 * obj = JSONObject.fromObject(product); ApiT_products
				 * cur_t_product = (ApiT_products) obj.toBean(obj,
				 * ApiT_products.class);
				 * apiErpService.productStock4erp(cur_t_product); }
				 */
			}
			mv.addObject("goods", goods);
			mv.addObject("isEdit", 1);// 用于在页面上判断是不是编辑某个商品
			ApiType goodsType = apiTypeService.findTypeById(goods.getType());
			mv.addObject("goodsType", goodsType);

			// 这个商品所在城市的其它商店
			conditions.put("cityId", goods.getCity_id());
			List<ApiShop> shops = apiShopsService.searchShops(conditions);
			mv.addObject("shops", shops);

			initializeTypes(mv, goodsType);

			// 商品已售数量
			Integer soldCount = goodService.getSoldedGoodsCount(Long.valueOf(id));
			mv.addObject("soldCount", soldCount);

			// products
			String products_list = "";
			List<ApiT_products> products = apiT_productsService.getUndeletedProductsByGoodsId(Long.valueOf(id));

			mv.addObject("products_list", products_list);
			mv.addObject("products", products);
			if (products.size() <= 0)
				mv.addObject("no_product", 1);
			else
				mv.addObject("no_product", 0);
			// goods' pics
			String image_list = "";
			List<ApiGoods_p> allGoodsImages = goodService.findAllGoodsPByGoodsId(Long.valueOf(id));
			List<ApiGoods_p> images = new ArrayList<ApiGoods_p>();
			List<ApiGoods_p> detailPics = new ArrayList<ApiGoods_p>();
			for (ApiGoods_p image : allGoodsImages) {
				if (image.getType() == 0) {// 商品的多图
					image_list += image.getPath() + ", ";
					images.add(image);
				} else if (image.getType() == 1) {// 商品详情图片
					detailPics.add(image);
				}
			}
			mv.addObject("images", images);
			mv.addObject("detailPics", detailPics);
			mv.addObject("image_list", image_list);
			mv.addObject("productSize", products.size());

		} else {// 新增商品

			List<ApiType> types1 = apiTypeService.getBigTypesZiYing();
			mv.addObject("types1", types1);
			mv.addObject("productSize", 1);// 用于在页面是标识规格 （规格1）
			List<ApiShop> shops = apiShopsService.searchShops(conditions);
			mv.addObject("shops", shops);
			taglist = apiT_goods_tagsService.findGoodsTagss(null);
		}
		Map paramMap = new HashMap();
		paramMap.put("status", 1);
		PageInfo page = new PageInfo();
		page.setCurrentPage(1);
		page.setShowCount(5000000);
		List<ApiT_member_entrepreneur> entrepreneurs = apiT_member_entrepreneurService
				.findT_member_entrepreneursByMap(paramMap, page);
		mv.addObject("entrepreneurs", entrepreneurs);
		mv.addObject("taglist", taglist);
		return mv;
	}

	/**
	 * 非自营店商品list
	 * 
	 * @return
	 */
	@RequestMapping(value = "goods-list2")
	public ModelAndView goods_list2(HttpServletRequest request, HttpServletResponse response, PageInfo pageInfo)
			throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/goods_list2.jsp");
		// c_mtype : 0用户 1 绑定商户 2 vip 9被屏蔽 3 配送员

		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("isZiYing", false);
		conditions.put("cEnable", true);

		List<ApiGoods> goods_list = goodService.searchGoods(conditions, pageInfo);
		mv.addObject("goods_list", goods_list);

		//
		List<ApiShop> shops = apiShopsService.searchShops(conditions);
		mv.addObject("shops", shops);

		List<ApiT_city> citys = startOnLoadService.citys();
		mv.addObject("citys", citys);

		List<ApiType> types = new ArrayList<ApiType>();
		List<ApiType> types1 = null;
		types1 = apiTypeService.getBigTypes();

		// 包含根级分类
		types.addAll(types1);
		List<ApiType> types2 = apiTypeService.getSecondTyes(false);
		types.addAll(types2);
		List<ApiType> types3 = apiTypeService.getThirdTypes(false);
		types.addAll(types3);

		mv.addObject("types1", types1);
		mv.addObject("types2", types2);
		mv.addObject("types3", types3);
		mv.addObject("types", types);

		mv.addObject("pageInfo", pageInfo);

		return mv;
	}

	/**
	 * 批量下架商品
	 * 
	 * @param goodsIds
	 *            商品id
	 * @param type
	 *            1:上架; 2:下架
	 */
	@RequestMapping(value = "goods-batch-out")
	public @ResponseBody Map<String, Object> goodsBatchOut(Long[] goodsIds, int status) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			goodService.batchUpdateGoodsStatus(goodsIds, status);
			result.put("error", "0000");
			result.put("information", "更新成功");
		} catch (Exception ex) {
			ex.printStackTrace();
			result.put("error", "-1");
			result.put("information", "发生异常");
			logger.error(ex.getMessage());
		}
		return result;
	}

	/**
	 * 非自营新增商品
	 * 
	 * @return
	 */
	@RequestMapping(value = "goods-add-pre2")
	public ModelAndView goods_add_pre2(HttpServletRequest request, HttpServletResponse response, boolean isZiYing)
			throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/goods_add2.jsp");
		//
		List<ApiT_city> citys = startOnLoadService.citys();
		mv.addObject("citys", citys);

		HashMap map = new HashMap();
		map.put("disabled", 1);// 可用的品牌
		// 加载品牌列表
		List<ApiT_brand> brandList = apiT_brandService.findT_brandsByMap(map);
		mv.addObject("brandList", brandList);

		List<ApiType> promotion_types = startOnLoadService.promotion_types();
		mv.addObject("promotion_types", promotion_types);

		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("isZiYing", false);
		conditions.put("cEnable", true);
		// 获取商品标签列表
		List<ApiT_goods_tags> taglist = new ArrayList<ApiT_goods_tags>();
		// 请求编辑某个goods
		if (request.getParameter("id") != null) {
			String id = request.getParameter("id");
			taglist = apiT_goods_tagsService.findGoodsTagss(Long.valueOf(id));
			ApiGoods goods = goodService.findT_goodsById(Long.valueOf(id));
			if (goods != null) {
				// 根据商品编码同步
				List<Map<String, Object>> cur_t_products = apiT_productsService.findProductsByGoodsId(Long.valueOf(id));
				for (Map<String, Object> product : cur_t_products) {
					Object _str_erp_product_id = product.get("product_id");
					JSONObject obj = JSONObject.fromObject(product);
					ApiT_products cur_t_product = (ApiT_products) obj.toBean(obj, ApiT_products.class);
					apiErpService.productStock4erp(cur_t_product);
				}
			}
			// 这个商品和商品类型
			mv.addObject("goods", goods);
			mv.addObject("isEdit", 1);// 用于在页面上判断是不是编辑某个商品
			ApiType goodsType = apiTypeService.findTypeById(goods.getType());
			mv.addObject("goodsType", goodsType);

			// 这个商品所在城市的其它商店
			conditions.put("cityId", goods.getCity_id());
			List<ApiShop> shops = apiShopsService.searchShops(conditions);
			mv.addObject("shops", shops);

			List<ApiType> subTypes = null;
			ApiShop shopOfGoods = apiShopsService.findShopByCid(goods.getShop_id() + "");
			ApiType shopType = apiTypeService.findTypeById(shopOfGoods.getcType());// 商品所属的类型
			mv.addObject("shopType", shopType);

			initializeTypes(mv, goodsType);

			// 商品已售数量
			Integer soldCount = goodService.getSoldedGoodsCount(Long.valueOf(id));
			mv.addObject("soldCount", soldCount);

			// products
			String products_list = "";
			List<ApiT_products> products = apiT_productsService.getUndeletedProductsByGoodsId(Long.valueOf(id));

			mv.addObject("products_list", products_list);
			mv.addObject("products", products);
			if (products.size() <= 0)
				mv.addObject("no_product", 1);
			else
				mv.addObject("no_product", 0);
			// goods' pics
			String image_list = "";
			List<ApiGoods_p> allGoodsImages = goodService.findAllGoodsPByGoodsId(Long.valueOf(id));
			List<ApiGoods_p> images = new ArrayList<ApiGoods_p>();
			List<ApiGoods_p> detailPics = new ArrayList<ApiGoods_p>();
			for (ApiGoods_p image : allGoodsImages) {
				if (image.getType() == 0) {// 商品的多图
					image_list += image.getPath() + ", ";
					images.add(image);
				} else if (image.getType() == 1) {// 商品详情图片
					detailPics.add(image);
				}
			}

			mv.addObject("images", images);
			mv.addObject("detailPics", detailPics);
			mv.addObject("image_list", image_list);
			mv.addObject("productSize", products.size());
		} else {// 新增商品
			List<ApiType> types1 = apiTypeService.getBigTypesZiYing();
			mv.addObject("types1", types1);
			mv.addObject("productSize", 1);// 用于在页面是标识规格 （规格1）
			List<ApiShop> shops = apiShopsService.searchShops(conditions);
			mv.addObject("shops", shops);
			taglist = apiT_goods_tagsService.findGoodsTagss(null);
			// List<ApiType> types1 = apiTypeService.getBigTypes();
			// mv.addObject("types1", types1);
			// mv.addObject("productSize", 1);// 用于在页面是标识规格 （规格1）
		}
		//
		mv.addObject("taglist", taglist);
		return mv;
	}

	/**
	 * 进入某个商店添加商品（非自营）
	 * 
	 * @return
	 */
	@RequestMapping(value = "add-shop-goods")
	public ModelAndView addShopGoods(Integer shopId) {

		ModelAndView mv = new ModelAndView("forward:/backstage/add-shop-goods.jsp");
		ApiShop shop = apiShopsService.findShopByCid(shopId + "");
		ApiT_city city = apiT_cityService.findT_cityById(shop.getC_city_id());
		mv.addObject("shop", shop);
		mv.addObject("city", city);
		return mv;
	}

	/**
	 * 
	 * @param typeId
	 *            这个店所属的类别
	 * @param shopId
	 *            这个店的id
	 * @return
	 */
	@RequestMapping(value = "shop-type-info")
	public @ResponseBody Map<String, Object> shopTypeInfo(Integer typeId, Integer shopId) {
		Map<String, Object> result = new HashMap<String, Object>();
		ApiType shopType = apiTypeService.findTypeById(typeId);
		if (shopType != null) {
			List<ApiType> subTypes = null;
			result.put("shopType", shopType);
			if (shopType.getcBelong() != 0) {// 这个店属于二级目录
				ApiType topType = apiTypeService.findTypeById(shopType.getcBelong());
				if (isMeiShiClassify(topType.getcCode())) {// 美食外卖，可以自己建分类
					result.put("typeStatus", 10);
					subTypes = apiTypeService.getShopTypes(shopId);
					result.put("subTypes", subTypes);
				} else {
					result.put("typeStatus", 2);// 不能再有自己的分类
				}
			} else {// 这个店属于一级目录
					// 得到它的子目录
				result.put("typeStatus", 1);
				subTypes = apiTypeService.gettwoType(shopType.getcCode());
				result.put("subTypes", subTypes);
			}
		}
		return result;
	}

	/**
	 * 判断某个分类是不是美食
	 * 
	 * @param typeId
	 * @return
	 */
	private boolean isMeiShiClassify(int typeId) {
		String meiShi = startOnLoadService.dictionaryMap().get("MENU_MEISHI");
		int meiShiId = -1;
		try {
			meiShiId = Integer.parseInt(meiShi);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return typeId == meiShiId;
	}

	/**
	 * 编辑自营商品时，初始化类别选择框
	 * 
	 * @param mv
	 * @param goodsType
	 */
	private void initializeTypes(ModelAndView mv, ApiType goodsType) {
		List<ApiType> types1 = apiTypeService.getBigTypesZiYing();
		mv.addObject("types1", types1);

		// c_belong = 0 and c_grade = 0//属于第一级目录
		if (goodsType.getcBelong().intValue() == 0 && goodsType.getcGrade().intValue() == 0) {
			mv.addObject("firstType", goodsType);
			// c_belong = c_grade and c_belong != 0 //属于第二级目录
		} else if (goodsType.getcBelong().intValue() == goodsType.getcGrade().intValue()
				&& goodsType.getcBelong() != 0) {
			List<ApiType> allSeconedTypes = apiTypeService.getSecondTypes();
			List<ApiType> types2 = new ArrayList<ApiType>();

			for (ApiType type : allSeconedTypes) {
				if (type.getcBelong().intValue() == goodsType.getcBelong().intValue()) {
					types2.add(type);
				}
			}
			mv.addObject("types2", types2);

			ApiType firstType = apiTypeService.findTypeById(goodsType.getcBelong());
			mv.addObject("firstType", firstType);

			mv.addObject("sencondType", goodsType);
		} else if (goodsType.getcBelong().intValue() != goodsType.getcGrade().intValue()) {// 属于第三级目录
																							// and
																							// c_belong
																							// !=
																							// c_grade
			List<ApiType> allSeconedTypes = apiTypeService.getSecondTyes(true);
			List<ApiType> allThirdTypes = apiTypeService.getThirdTypes(true);

			ApiType sencondType = apiTypeService.findTypeById(goodsType.getcBelong());
			mv.addObject("sencondType", sencondType);

			ApiType firstType = apiTypeService.findTypeById(sencondType.getcBelong());
			mv.addObject("firstType", firstType);

			List<ApiType> types2 = new ArrayList<ApiType>();// 和要编辑的商品所属同一级的的第二级分类
			List<ApiType> types3 = new ArrayList<ApiType>();// 和要编辑的商品所属同一级的的第三级分类

			for (ApiType type : allSeconedTypes) {
				if (type.getcBelong().intValue() == sencondType.getcBelong().intValue()) {
					types2.add(type);
				}
			}

			for (ApiType type : allThirdTypes) {
				if (type.getcBelong().intValue() == goodsType.getcBelong().intValue()) {
					types3.add(type);
				}
			}

			mv.addObject("types2", types2);
			mv.addObject("types3", types3);

			mv.addObject("thiredType", goodsType);
		}

	}

	/**
	 * 得到不得级别的分类
	 * 
	 * @param level
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "get-types")
	public @ResponseBody List<ApiType> getTypes(Integer level, boolean isZiYing) throws Exception {
		List<ApiType> types = null;
		if (level == null || level == 1) {
			if (!isZiYing) {
				types = apiTypeService.getBigTypes();
			} else {
				types = apiTypeService.getBigTypesZiYing();
			}
		} else if (level == 2) {
			types = apiTypeService.getSecondTyes(isZiYing);
		} else if (level == 3) {
			types = apiTypeService.getThirdTypes(isZiYing);
		}
		return types;
	}

	/**
	 * 获取选中分类的子分类
	 * 
	 * @param level
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "get-types-chil")
	public @ResponseBody List<ApiType> getTypesChil(Integer typeid) throws Exception {
		List<ApiType> types = new ArrayList<ApiType>();
		types = apiTypeService.gettwoType(typeid);
		return types;
	}

	/**
	 * 得到所有的商铺
	 * 
	 * @param level
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "get-all-shops")
	public @ResponseBody List<ApiShop> getShops(boolean isZiYing) throws Exception {
		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("isZiYing", isZiYing);
		conditions.put("cEnable", true);
		return apiShopsService.searchShops(conditions);
	}

	/**
	 * 得到所有的商铺
	 * 
	 * @param level
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "get-all-shops1")
	public @ResponseBody List<ApiShop> getShops1() throws Exception {
		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("isZiYing", false);
		conditions.put("cEnable", true);
		conditions.put("all", true);
		return apiShopsService.searchShops(conditions);
	}

	/**
	 * 保存商品
	 * 
	 * @param request
	 * @param response
	 * @param detailPic
	 *            商品详情图片
	 * @param deletePic
	 *            要删除的详情图片
	 * @throws Exception
	 */
	@Transactional
	@RequestMapping(value = "goods-add")
	public void goods_add(HttpServletRequest request, HttpServletResponse response, String[] detailPic,
			String[] deletePic) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String entId = request.getParameter("ent_id");
			String name = request.getParameter("name");
			String city_id = request.getParameter("city_id");
			String shop_id = request.getParameter("shop_id");
			String mini_buy = request.getParameter("mini_buy");
			String image = request.getParameter("image");
			String type = request.getParameter("type");
			String sort = request.getParameter("sort");
			String producing_area = request.getParameter("producing_area");
			String count = request.getParameter("count");
			String description = request.getParameter("description");
			String is_deleted = request.getParameter("is_deleted");
			//
			String products_list = request.getParameter("products_list");
			String image_list = request.getParameter("image_list"); // 商品介绍图里的图片
			String image_list_del = request.getParameter("image_list_del");
			String status = request.getParameter("status");
			String property = request.getParameter("property");
			String price = request.getParameter("price");
			String brand_id = request.getParameter("brand_id");
			String group_flag = request.getParameter("group_flag");
			if (group_flag == null || "".equals(group_flag)) {
				group_flag = "1";
			}
			String col_img = request.getParameter("col_img");
			String[] goodstagsid = request.getParameterValues("goodstags");

			String id = request.getParameter("id");

			if (id == null || (id.trim()).equals("")) {// add
				ApiGoods t_good = new ApiGoods();
				t_good.setUserId(entId);
				t_good.setName(name);
				t_good.setCity_id(0);
				t_good.setShop_id(0);
				t_good.setMini_buy(Integer.valueOf(mini_buy));
				t_good.setCount(Integer.valueOf(count));
				t_good.setSort(Integer.valueOf(sort));
				t_good.setProducing_area(producing_area);
				t_good.setType(Integer.valueOf(type));
				t_good.setDescription(description);
				t_good.setImage(image);
				t_good.setStatus(status);
				t_good.setProperty(property);
				String creteTime = DateUtil.nowTimeToString();
				t_good.setCreate_time(creteTime);
				t_good.setUpdate_time(creteTime);
				t_good.setGroup_flag(Integer.valueOf(group_flag));
				t_good.setCol_img(col_img);
				t_good.setSpec("");
				t_good.setPromotion_type(0);
				t_good.setPar_type(0);
				t_good.setIs_top(0);
				t_good.setPromotion_image("");
				if (price != null)
					t_good.setPrice(Double.valueOf(price));
				if (brand_id != null)
					t_good.setBrand_id(Integer.valueOf(brand_id));
				goodService.insertT_goodsAll(t_good, products_list, image_list, detailPic, goodstagsid);
				id = t_good.getId() + "";
			} else {// edit
				ApiGoods t_good = goodService.findT_goodsById(Long.valueOf(id));

				t_good.setUserId(entId);
				t_good.setName(name);
				t_good.setCity_id(0);
				t_good.setShop_id(0);
				t_good.setMini_buy(Integer.valueOf(mini_buy));
				t_good.setCount(Integer.valueOf(count));
				t_good.setSort(Integer.valueOf(sort));
				t_good.setProducing_area(producing_area);
				t_good.setType(Integer.valueOf(type));
				t_good.setIs_deleted(Integer.valueOf(is_deleted));
				t_good.setDescription(description);
				t_good.setImage(image);
				t_good.setStatus(status);
				t_good.setProperty(property);
				t_good.setGroup_flag(Integer.valueOf(group_flag));
				t_good.setCol_img(col_img);
				if (price != null)
					t_good.setPrice(Double.valueOf(price));
				if (brand_id != null)
					t_good.setBrand_id(Integer.valueOf(brand_id));
				// Date updateTime = new Date();
				t_good.setUpdate_time(DateUtil.nowTimeToString());
				if (image_list_del == null)
					image_list_del = ",";
				int ret_i = goodService.updateT_goodsAll(t_good, products_list, image_list, image_list_del, deletePic,
						detailPic);
				// 删除原来商品与标签的关系表数据
				apiT_goods_tags_linkService.deleteGoodsTagsLinkByGoodid(Long.valueOf(id));
				if (goodstagsid != null && goodstagsid.length != 0) {
					List<ApiT_goods_tags_link> list = new ArrayList<ApiT_goods_tags_link>();
					for (String tagid : goodstagsid) {
						ApiT_goods_tags_link apiT_goods_tags_link = new ApiT_goods_tags_link();
						apiT_goods_tags_link.setGtag_id(Integer.valueOf(tagid));
						apiT_goods_tags_link.setGoods_id(Long.valueOf(id));
						list.add(apiT_goods_tags_link);
					}
					apiT_goods_tags_linkService.insertGoodsTagsLinks(list);
				}
			}
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "添加成功！");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 上传缩略图
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "goods-smallpic-upload")
	public void goods_smallpic_upload(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String pic_path = ImageUtils.uploadFile(request, "/goods/", file);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "上传成功！");
			map.put("datas", pic_path);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "上传失败！");
		}
		//
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 上传文件
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "goods-pics-upload")
	public void goods_pics_upload(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		String goodsid = "2"; // request.getParameter("goodsid");
		// goodsid = "1";
		String path = ImageUtils.getServletWebAppsPath(request) + "/goods/";
		String fileName = goodsid + "_" + file.getOriginalFilename();
		// System.out.println(path);
		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		// 保存
		try {
			file.transferTo(targetFile);
			ApiGoods_p p = new ApiGoods_p();
			p.setGoodsId(Long.valueOf(goodsid));
			p.setFileName(fileName);
			p.setPath(ImageUtils.getDataBaseImagePath() + "/goods/" + goodsid + "_" + fileName);
			p.setCommit_time(new Date());
			p.setNote(request.getParameter("note"));
			p.setStatus(0);
			goodService.insertGoods_p(p);

			Map<String, Object> map = new HashMap<String, Object>();
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put("datas", p);
			map.put(Utils.MESSAGE, "上传成功！");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			out.print(JsonUtil.object2json(map));
			out.close();
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		// model.addAttribute("fileUrl",
		// request.getContextPath()+"/upload/"+fileName);
		// return "result";
	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	@RequestMapping(value = "goods-disable")
	public void goods_disable(HttpServletRequest request, HttpServletResponse response) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");

		// virtual-delete
		ApiGoods goods = goodService.findT_goodsById(Long.valueOf(id));
		goods.setIs_deleted(1);
		int ret_i = goodService.updateT_goods(goods);

		//
		if (ret_i > 0) {
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "软删除成功！");
		}
		response.setCharacterEncoding("UTF-8");
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	@RequestMapping(value = "products-disable")
	public void products_disable(HttpServletRequest request, HttpServletResponse response) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");

		// virtual-delete
		ApiT_products product = apiT_productsService.findT_productsById(Long.valueOf(id));
		product.setIs_delete(1);
		int ret_i = apiT_productsService.updateT_products(product);

		//
		if (ret_i > 0) {
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "软删除成功！");
		}
		response.setCharacterEncoding("UTF-8");
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 进入查询界面
	 * 
	 * @return
	 */
	@Transactional
	@RequestMapping(value = "/goods/toQuery")
	public ModelAndView toQuery(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/views/backstage/manage/goodsQuery.jsp");
		return mv;
	}

	/**
	 * 查询
	 * 
	 * @return
	 */
	@Transactional
	@RequestMapping(value = "/goods/query")
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String name = request.getParameter("name");
		String cityid = request.getParameter("cityid");
		if ((name == null) || (name.equals("null"))) {
			name = "";
		}
		List<Map<String, Object>> datas = goodService.searchGoods(name, cityid);
		ModelAndView mv = new ModelAndView("forward:/views/backstage/manage/goodsResult.jsp");
		mv.addObject("datas", datas);
		mv.addObject("totalRows", datas.size());
		return mv;
	}

	/**
	 * 进入新增界面
	 * 
	 * @return
	 */
	@Transactional
	@RequestMapping(value = "/goods/toAdd")
	public ModelAndView toAdd(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/views/backstage/manage/goodsAdd.jsp");
		ApiGoods good = new ApiGoods();
		mv.addObject("good", good);
		return mv;
	}

	/**
	 * 新增
	 * 
	 * @return
	 */
	@Transactional
	@RequestMapping(value = "/goods/add")
	public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String name = request.getParameter("name");
		String mini_buy = request.getParameter("mini_buy");
		String description = request.getParameter("description");
		if (name != null && !"".equals(name.trim())) {
			ApiGoods t_good = new ApiGoods();
			t_good.setName(name);
			t_good.setMini_buy(Integer.valueOf(mini_buy));
			t_good.setDescription(description);
			goodService.insertT_goods(t_good);
		}
		ModelAndView mv = new ModelAndView("redirect:/views/backstage/manage/goodsQuery.jsp");
		return mv;
	}

	/**
	 * 进入修改界面
	 * 
	 * @return
	 */
	@Transactional
	@RequestMapping(value = "/goods/toUpdate")
	public ModelAndView toUpdate(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		List<Map<String, Object>> datas = goodService.getGoods(id);
		ModelAndView mv = new ModelAndView("forward:/views/backstage/manage/goodsUpdate.jsp");
		mv.addObject("datas", datas);
		return mv;
	}

	/**
	 * 修改
	 * 
	 * @return
	 */
	@Transactional
	@RequestMapping(value = "/goods/update")
	public ModelAndView update(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String name = request.getParameter("name");
		String mini_buy = request.getParameter("mini_buy");
		String description = request.getParameter("description");
		if (name != null && !"".equals(name.trim())) {
			ApiGoods t_good = new ApiGoods();
			t_good.setName(name);
			t_good.setMini_buy(Integer.valueOf(mini_buy));
			t_good.setDescription(description);
			goodService.updateT_goods(t_good);
		}
		ModelAndView mv = new ModelAndView("redirect:/views/backstage/manage/goodsQuery.jsp");
		return mv;
	}

	/**
	 * 专场列表
	 * 
	 * @author JW
	 * @param request
	 * @param response
	 * @param pageInfo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "speChangList")
	public ModelAndView speChangList(HttpServletRequest request, HttpServletResponse response, PageInfo pageInfo)
			throws Exception {

		ModelAndView mv = new ModelAndView("forward:/backstage/speChang_list.jsp");
		List<Map<String, Object>> typesMap = goodService.getAllGoodTypes();

		mv.addObject("types", typesMap);
		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("scName", request.getParameter("scName"));
		conditions.put("type", request.getParameter("type"));

		String curDayStr = DateTimeUtil.getTimeByStyle("yyyy-MM-dd");
		Date curDay = DateTimeUtil.stringToDate(curDayStr);
		int curHour = Integer.parseInt(DateTimeUtil.getTimeByStyle("HH"));
		List<ApiSpeicalChang> list = goodService.searchSpecailChangList(conditions, pageInfo);
		for (ApiSpeicalChang apiSpeicalChang : list) {
			Date startDate = DateTimeUtil.stringToDate(apiSpeicalChang.getStart_date());
			int startHour = Integer.parseInt(apiSpeicalChang.getStart_time().substring(0, 2));
			int endHour = Integer.parseInt(apiSpeicalChang.getEnd_time().substring(0, 2));
			if (DateTimeUtil.getMillisecondsOfTwoDate(curDay, startDate) < 0) {
				apiSpeicalChang.setStatusTip(0);// 即将开始
			} else if (DateTimeUtil.getMillisecondsOfTwoDate(curDay, startDate) > 0) {
				apiSpeicalChang.setStatusTip(2);// 已借宿
			} else if (curDayStr.equals(apiSpeicalChang.getStart_date())
					&& (curHour >= startHour && curHour < endHour)) {
				apiSpeicalChang.setStatusTip(1);// 进行中
			} else if (curDayStr.equals(apiSpeicalChang.getStart_date()) && (curHour < startHour)) {
				apiSpeicalChang.setStatusTip(0);// 即将开始
			} else if (curDayStr.equals(apiSpeicalChang.getStart_date()) && (curHour > endHour)) {
				apiSpeicalChang.setStatusTip(2);// 已结束
			}
		}
		mv.addObject("pageInfo", pageInfo);
		mv.addObject("list", list);
		return mv;
	}

	/**
	 * 去添加专场页面
	 * 
	 * @author JW
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "speicalChangAdd")
	public ModelAndView speicalChangAdd(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/speicalChang_add.jsp");
		List<Map<String, Object>> typesMap = goodService.getAllGoodTypes();
		mv.addObject("types", typesMap);
		TreeMap<String, Object> timeMap = apiT_goods_topicService.getSpecailChangTimes();
		mv.addObject("timeMap", timeMap);

		Map paramMap = new HashMap();
		paramMap.put("status", 1);
		PageInfo page = new PageInfo();
		page.setCurrentPage(1);
		page.setShowCount(5000000);
		List<ApiT_member_entrepreneur> entrepreneurs = apiT_member_entrepreneurService
				.findT_member_entrepreneursByMap(paramMap, page);
		mv.addObject("entrepreneurs", entrepreneurs);
		return mv;
	}

	/**
	 * 添加专场
	 * 
	 * @author JW
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "addSpeicalChang")
	@ResponseBody
	public void addSpeicalChang(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<>();
		try {
			String msg = "";
			String topicId = request.getParameter("topicId");
			String goodsStr = request.getParameter("goodsStr");
			ApiSpeicalChang apiSpeicalChang = new ApiSpeicalChang();
			apiSpeicalChang.setType_id(request.getParameter("typeId"));
			apiSpeicalChang.setStart_time(request.getParameter("hour").split("-")[0]);
			apiSpeicalChang.setEnd_time(request.getParameter("hour").split("-")[1]);
			apiSpeicalChang.setTitle(request.getParameter("title"));
			apiSpeicalChang.setTopic_img(request.getParameter("topicImg"));
			apiSpeicalChang.setStart_date(request.getParameter("start_date"));
			apiSpeicalChang.setMember_id(request.getParameter("entId"));
			// apiSpeicalChang.setDiscount(Util.getBigDecimal(request.getParameter("discount")));
			if (Util.isNull(topicId)) {
				goodService.addSpeicalChang(apiSpeicalChang);
				msg = "添加成功";
			} else {
				apiSpeicalChang.setTopic_id(Integer.parseInt(topicId));
				apiT_goods_topicService.updGoodsTopic(apiSpeicalChang);
				if (!Util.isNull(goodsStr) && !goodsStr.equals("暂无数据")) {
					apiT_goods_topic_linkService.delTopicLinkByCondition(topicId, null);
					String goodsArr[] = goodsStr.split(",");
					List<ApiGoodsTopicLink> list = new ArrayList<>();
					ApiGoodsTopicLink apiGoodsTopicLink = null;
					for (int i = 0; i < goodsArr.length; i++) {
						apiGoodsTopicLink = new ApiGoodsTopicLink();
						apiGoodsTopicLink.setTopic_id(topicId);
						apiGoodsTopicLink.setGoods_id(goodsArr[i]);
						list.add(apiGoodsTopicLink);
					}
					goodService.batchInsertTopicLink(list);
				}
				msg = "修改成功";
			}

			map.put(Utils.MESSAGE, msg);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			map.put(Utils.MESSAGE, "系统异常");
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
		}
		response.setCharacterEncoding("UTF-8");
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 去修改专场页面
	 * 
	 * @author JW
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "goSpeicalChangEdit")
	public ModelAndView goSpeicalChangEdit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/speicalChang_add.jsp");
		List<Map<String, Object>> typesMap = goodService.getAllGoodTypes();
		mv.addObject("types", typesMap);
		TreeMap<String, Object> timeMap = apiT_goods_topicService.getSpecailChangTimes();
		mv.addObject("timeMap", timeMap);

		ApiT_goods_topic topicMap = apiT_goods_topicService.getTopicByTopicId(request.getParameter("topicId"));
		mv.addObject("time", topicMap.getStart_time() + "-" + topicMap.getEnd_time());
		mv.addObject("topicMap", topicMap);
		List<Map<String, Object>> goodList = apiT_goods_topicService
				.getGoodsInfoByTopicId(request.getParameter("topicId"), null, 0, 10000);
		mv.addObject("goodList", goodList);

		Map paramMap = new HashMap();
		paramMap.put("status", 1);
		PageInfo page = new PageInfo();
		page.setCurrentPage(1);
		page.setShowCount(5000000);
		List<ApiT_member_entrepreneur> entrepreneurs = apiT_member_entrepreneurService
				.findT_member_entrepreneursByMap(paramMap, page);
		mv.addObject("entrepreneurs", entrepreneurs);
		mv.addObject("memberId", topicMap.getMember_id());
		mv.addObject("flag", "yes");
		return mv;
	}

	/**
	 * 删除专场商品
	 * 
	 * @author jw
	 * 
	 */
	@RequestMapping(value = "topic-goods-delete")
	public void topss(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<>();
		try {
			apiT_goods_topic_linkService
					.deleteT_goods_topic_link(Integer.parseInt(request.getParameter("topicLinkId")));
			map.put(Utils.MESSAGE, "删除成功");
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		} catch (Exception e) {
			map.put(Utils.MESSAGE, "删除失败");
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			e.printStackTrace();
		}
		response.setCharacterEncoding("UTF-8");
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 删除专场
	 * 
	 * @author jw
	 * 
	 */
	@RequestMapping(value = "delSpecailChangById")
	public void delSpecailChangById(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<>();
		try {
			String id = request.getParameter("id");
			apiT_goods_topicService.delGoodsTopic(id);
			map.put(Utils.MESSAGE, "删除成功");
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		} catch (Exception e) {
			map.put(Utils.MESSAGE, "删除失败");
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			e.printStackTrace();
		}
		response.setCharacterEncoding("UTF-8");
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 添加商品弹窗
	 * 
	 * @author JW
	 * @param request
	 * @param response
	 * @param pageInfo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "speChangForDialog")
	public ModelAndView speChangForDialog(HttpServletRequest request, HttpServletResponse response, PageInfo pageInfo)
			throws Exception {
		// ModelAndView mv = new
		// ModelAndView("forward:/backstage/speChang_list.jsp");
		ModelAndView mv = new ModelAndView("forward:/backstage/select_goods_for_specail_chang.jsp");
		List<ApiGoods> goodList = goodService.searchGoodsByType(Integer.parseInt(request.getParameter("typeId")),
				request.getParameter("topicId"), "", request.getParameter("memberId"));
		mv.addObject("goods_list", goodList);
		mv.addObject("topicId", request.getParameter("topicId"));
		return mv;
	}

	/**
	 * 批量插入专场商品
	 * 
	 * @author JW
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "batchInsertTopicLink")
	public @ResponseBody void batchInsertTopicLink(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String[] goodIds = null;
			String pString = request.getParameter("goodsId");
			if (pString != null && pString != "") {
				goodIds = request.getParameter("goodsId").split(",");
			}
			String topicId = request.getParameter("topicId");
			List<ApiGoodsTopicLink> list = new ArrayList<ApiGoodsTopicLink>();
			ApiGoodsTopicLink apiGoodsTopicLink = null;
			if (goodIds != null && topicId != null) {
				for (int i = 0; i < goodIds.length; i++) {
					apiGoodsTopicLink = new ApiGoodsTopicLink();
					apiGoodsTopicLink.setTopic_id(topicId);
					apiGoodsTopicLink.setGoods_id(goodIds[i]);
					// apiGoodsTopicLink.setProduct_id(productId[i]);
					// apiGoodsTopicLink.setType_id(typeIds[i]);
					list.add(apiGoodsTopicLink);
				}
				goodService.batchInsertTopicLink(list);
			}
			map.put(Utils.MESSAGE, "添加成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put(Utils.MESSAGE, "添加失败");
		}
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}
}
